package main

import (
	"context"
	"log"
	"time"
        "net"
        "net/http"
        "net/rpc"
        "os"
	"fmt"
	"go.etcd.io/etcd/clientv3"
)

// 算数运算结构体
type Arith struct {
}

// 算数运算请求结构体
type ArithRequest struct {
    A string
    B []byte
}

// 算数运算响应结构体
type ArithResponse struct {
    Pro int // 乘积
    Quo int // 商
    Rem int 

}


func (this *Arith) Multiply(req ArithRequest, res *ArithResponse) error {



	res.Pro = 10



	return nil
}



// 除法运算方法
func (this *Arith) Divide(req ArithRequest, res *ArithResponse) error {
    
	return nil
}

func rpc_server() {
    rpc.Register(new(Arith)) // 注册rpc服务
    rpc.HandleHTTP()         // 采用http协议作为rpc载体

    lis, err := net.Listen("tcp", "127.0.0.1:8095")
    if err != nil {
        log.Fatalln("fatal error: ", err)
    }

    fmt.Fprintf(os.Stdout, "%s", "start connection")

    http.Serve(lis, nil)
}



func getValue() {
	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{"localhost:2379"},
		DialTimeout: 5 * time.Second,
	})

	if err != nil {
		log.Println("connect to etcd failed, err:", err)
		return
	}
	defer cli.Close()
     


	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
	putResp, err := cli.Put(ctx, "fruit", "orange")
	cancel()

	if err != nil {
		log.Println("put to ectcd failed:", err)
		return
	}
	log.Println("putResp:", putResp)

	ctx, cancel = context.WithTimeout(context.Background(), 1*time.Second)
	getResp, err := cli.Get(ctx, "fruit")
	cancel()
	if err != nil {
		log.Printf("get from etcd failed, err:%v\n", err)
		return
	}

	log.Println("getResp:", getResp)

	for _, ev := range getResp.Kvs {
		log.Printf("%s:%s\n", ev.Key, ev.Value)
	}
}

func main(){

   getValue()
   rpc_server()
}


